

package PDFd.Instance;

import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Base64;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* <p>Title: BitmapConverter</p>
* <p>Description:  * This uses the XStream interface to provide android-friendly seralization of the Android Bitmap Drawable.
 * Upon marshalling this will take the bitmap, render it as a png, base64 encode it, then write it to the filer.
 * Upon unmarshalling it will base64 decode it, then ask the bitmap factory to decode the png into a bitmap. 
 * Its all p. slick.</p>
* @author Matt, Tom, Andrew, Kong
* @email matt.mckay@my.uwrf.edu,tom.florin@my.uwrf.edu,
* andrew.kathan@my.uwrf.edu,kong.xiong-1@my.uwrf.edu
* @date December 1st,2011*/

public class BitmapConverter implements Converter {
	public boolean canConvert(@SuppressWarnings("rawtypes") Class arg0) {
		return Bitmap.class == arg0;
	}

	/**
	 * Takes the bit map and compiles it into a PNG, encode it and write
	 * it to the filer.
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 */
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
		Bitmap b = (Bitmap) arg0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
		b.compress(CompressFormat.PNG, 0, bos);
		arg1.setValue(Base64.encodeToString(bos.toByteArray(), Base64.DEFAULT));
	}

	/**
	 * Takes the bit map and decompiles it.
	 * @param arg0
	 * @param arg1
	 * @return
	 */
	public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
		byte[] bitmap = Base64.decode(arg0.getValue(), Base64.DEFAULT);
		Bitmap obj = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
		return obj;
	}

}
